package com.cloudcc.mobile.adapter;

import java.io.File;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

import com.cloudcc.cloudframe.model.DynamicModel.FeedFile;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.util.ImageUtils;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.util.photo.Constants;
import com.cloudcc.mobile.view.activity.ImagePagerActivity;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

/** * 9张图片适配器 * */
public class IndexGridViewAdapter extends BaseAdapter {
	private Context context;
	private List<FeedFile> list;
	private OnShowImageListener onShowImageListener;

	public IndexGridViewAdapter(Context context, List<FeedFile> list) {
		this.context = context;
		this.list = list;
	}

	public void setOnShowImageListener(OnShowImageListener onShowImageListener) {
		this.onShowImageListener = onShowImageListener;
	}

	// 设置更新界面
	public void changeData(List<FeedFile> list) {
		this.list = list;
		notifyDataSetChanged();
	}

	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public FeedFile getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = LayoutInflater.from(context).inflate(
					R.layout.gridview_item, null);
			holder.v = (ImageView) convertView.findViewById(R.id.item);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		FeedFile f = list.get(position);
		// 动态修改imageVIew大小
		LayoutParams para;
		para = holder.v.getLayoutParams();
		if (list.size() == 1) {
			para.height = LayoutParams.WRAP_CONTENT;
			para.width = LayoutParams.WRAP_CONTENT;
			holder.v.setMaxWidth(AppContext.screenW * 2 / 3);
			holder.v.setMaxHeight(AppContext.screenH / 2);
			holder.v.setScaleType(ScaleType.FIT_XY);
		} else if (list.size() == 4) {
			para.height = AppContext.screenW * 4 / 15;
			para.width = AppContext.screenW * 4 / 15;
			holder.v.setScaleType(ScaleType.CENTER_CROP);
		} else {
			para.height = AppContext.screenW * 4 / 15;
			para.width = AppContext.screenW * 4 / 15;
			holder.v.setScaleType(ScaleType.CENTER_CROP);
		}
		holder.v.setLayoutParams(para);

		// 根据f的id取图片附在v上
		String id = f.fileid;
		String type = f.contentType;
		String pic = id + "." + type;
		String path = Tools.getImagePath("/CloudCC/Chat/");
		if (!new File(path).exists()) {
			new File(path).mkdirs();
		}
		String iconpath = Tools.getImagePath("/CloudCC/Chat/") + "/" + pic;
		File file = new File(iconpath);
		if (file.exists()) {
			ImageLoader.getInstance().displayImage("file://" + iconpath,
					holder.v, Constants.chater_index_option_image);
		} else {
			ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener(
					pic, "/CloudCC/Chat/");
			String url = UrlTools.url + UrlTools.imgurlsee + id + "&binding="
					+ AppContext.binding;
			String replace = StringUtils.replace(url, "https://", "http://");
			ImageLoader.getInstance().displayImage(replace, holder.v,
					Constants.Index_options, animateFirstListener);

		}
		holder.v.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String[] imgs = new String[list.size()];
				String[] ids = new String[list.size()];
				for (int i = 0; i < list.size(); i++) {
					imgs[i] = UrlTools.url + UrlTools.imgurlsee
							+ list.get(i).fileid + "&binding="
							+ AppContext.binding;
					ids[i] = list.get(i).fileid + "." + list.get(i).contentType;
				}
				imageBrower(position, imgs, ids);
			}
		});
		return convertView;
	}

	private void imageBrower(int position, String[] urls, String[] ids) {
		Intent intent = new Intent(context, ImagePagerActivity.class);
		// 图片url,为了演示这里使用常量，一般从数据库中或网络中获取
		intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, urls);
		intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_FEEDFILES, ids);
		intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
		context.startActivity(intent);
	}

	class ViewHolder {
		private ImageView v;
	}

	public interface OnShowImageListener {
		public void show(int position);
	}

	private static class AnimateFirstDisplayListener extends
			SimpleImageLoadingListener {
		private String id;
		private String path;

		public AnimateFirstDisplayListener(String imageId, String path) {
			this.id = imageId;
			this.path = path;
		}

		static final List<String> displayedImages = Collections
				.synchronizedList(new LinkedList<String>());

		@Override
		public void onLoadingComplete(String imageUri, View view,
				Bitmap loadedImage) {
			if (loadedImage != null) {
				ImageView imageView = (ImageView) view;
				boolean firstDisplay = !displayedImages.contains(imageUri);
				if (firstDisplay) {
					FadeInBitmapDisplayer.animate(imageView, 500);
					displayedImages.add(imageUri);
					ImageUtils.saveImage(path, id, loadedImage);
				}
			}
		}
	}

}
